package gui;

import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import code.KeyStoreManager;
import code.Language;
import code.Settings;

public class AsymmetricKeyList extends JPanel {
	private static final long serialVersionUID = 1L;
	
	Color c= new Color(0x80, 0x80, 0xFF);
	private JScrollPane jScrollPane = null;
	private JTable jTable = null;
	private JLabel jLabel = null;
	ATOCOmain atocoframe;
	private KeyStoreManager ksm;
	private HashMap labels;

	private JLabel jLabel1 = null;
	String prevclassvalue;
	String mode;
	JPanel prevclass;
	
	public AsymmetricKeyList(ATOCOmain atocoframe, JPanel prevclass, String prevclassvalue, String mode) {
		super();
		Settings s = new Settings();
		Language l = new Language();
		labels = l.changeLanguage((String) s.global.get("language"), "AsymmetricKeyList", (String) s.global.get("installPath"));
		this.prevclass=prevclass;
		this.prevclassvalue=prevclassvalue;
		this.mode=mode;
		// Every Keystore operation must use this one.
		ksm = new KeyStoreManager(
				(String)Settings.global.get("personalKeyStoreFile"), 
				(String)Settings.global.get("personalKeyStorePassword"));
		if (ksm.getKeyStore() == null) {
        	System.out.println("Keystore file not found. Creating one.");
        	ksm.createKeyStore(
        			(String)Settings.global.get("personalKeyStoreFile"), 
    				(String)Settings.global.get("personalKeyStorePassword"));
        }
		this.atocoframe=atocoframe;
		initialize();
		
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		jLabel1 = new JLabel();
		jLabel1.setBounds(new Rectangle(532, 114, 127, 39));
		jLabel1.setText((String) labels.get("Use"));
		jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent e) {
				System.out.println(jTable.getValueAt(jTable.getSelectedRow(), 0).toString());
//				JPasswordField jpf = new JPasswordField();
//				int inputText = JOptionPane.showConfirmDialog(null, jpf,
//				  "Password:", JOptionPane.OK_CANCEL_OPTION);
				
				if(mode.equals("dec")) {
					JLabel label = new JLabel((String) labels.get("EnterKeyPassword"));
					JPasswordField jpf = new JPasswordField();
					JOptionPane.showConfirmDialog(null,
							new Object[]{label, jpf}, (String) labels.get("Password"),
							JOptionPane.OK_CANCEL_OPTION);

					if(!jpf.getText().equals("")){
						setprevclasskey(jTable.getValueAt(jTable.getSelectedRow(), 0).toString(), jpf.getText());
					}
				} else if(mode.equals("enc")) {
					setprevclasskey(jTable.getValueAt(jTable.getSelectedRow(), 0).toString(), "");
				}
			}
		});
		jLabel = new JLabel();
		jLabel.setBounds(new Rectangle(61, 17, 127, 16));
		jLabel.setText((String) labels.get("AsymmetricKeyList"));
		jLabel.setForeground(c);
		jLabel.setFont(new java.awt.Font("Dialog", Font.BOLD, 15));
		this.setSize(764, 417);
		this.setLayout(null);
		this.add(getJScrollPane(), null);
		this.setBackground(Color.WHITE);
		this.add(jLabel, null);
		this.add(jLabel1, null);
	}

	private void setprevclasskey(String keyAlias, String keyPassword){
		if(prevclassvalue.equalsIgnoreCase("Sign")){
			SignDigitalSignature sign=(SignDigitalSignature)prevclass;
//			sign.setKeys((PublicKey)ksm.getPublicKey(keyAlias),
//					(PrivateKey)ksm.getPrivateKey(keyAlias, keyPassword));
			sign.setKeyAndCert(ksm.getCertificate(keyAlias),
					(PrivateKey)ksm.getPrivateKey(keyAlias, keyPassword));
			atocoframe.contentPane(sign);
		} else if(prevclassvalue.equalsIgnoreCase("AsymmetricRSAEnc")){
			if(mode.equals("dec")) {
				AsymmetricRSAEncryption sign=(AsymmetricRSAEncryption)prevclass;
				sign.setKeyAndCert(ksm.getCertificate(keyAlias),
						(PrivateKey)ksm.getPrivateKey(keyAlias, keyPassword));
				atocoframe.contentPane(sign);
			} else if(mode.equals("enc")) {
				AsymmetricRSAEncryption sign=(AsymmetricRSAEncryption)prevclass;
				sign.setCert(ksm.getCertificate(keyAlias));
				atocoframe.contentPane(sign);
			}
		}
	}
	
	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setBounds(new Rectangle(60, 75, 441, 281));
			jScrollPane.setViewportView(getJTable());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jTable	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getJTable() {
		if (jTable == null) {
			
			Vector<Object> rowData = new Vector<Object>();
			
			HashSet<String> aliases = ksm.listAllKeys();
			Iterator it = aliases.iterator();
			while(it.hasNext()) {
				String al = (String) it.next();
				if (ksm.getPublicKey(al) == null) {
	        		// No certificate entry so it must be secretKey	
				} else {
					if (!ksm.getPublicKey(al).equals(null)) {
						// Has certificate entry so it must be KeyPair
						Vector<Object> row = new Vector<Object>();
						row.add(al);
						if(mode.equals("enc")) {
							row.add("Public Key");
						} else if(mode.equals("dec")) {
							row.add("Private Key");
						}
						rowData.add(row);
					}
				}
			}
			
			if(mode.equals("enc")) {
				HashSet<String> certaliases = ksm.listAllCerts();
				Iterator itcert = certaliases.iterator();
				while(itcert.hasNext()) {
					String al = (String) itcert.next();
					if (ksm.getPublicKey(al) == null) {
		        		// No certificate entry so it must be secretKey	
					} else {
						if (!ksm.getPublicKey(al).equals(null)) {
							// Has certificate entry so it must be KeyPair
							Vector<Object> row = new Vector<Object>();
							row.add(al);
							if(mode.equals("enc")) {
								row.add("Public Key");
							}
							rowData.add(row);
						}
					}
				}
			}
			
			Vector<String> columnNames = new Vector<String>();
			columnNames.add((String) labels.get("Alias"));
			columnNames.add((String) labels.get("Algorithm"));

			
			if (!rowData.isEmpty()) {
				DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
			
			jTable = new JTable(model);
			

		}
		
		}
		return jTable;
	}
}
